import Avatar from '@mui/material/Avatar'
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import React, { useState } from 'react'
import CardContent from '@mui/material/CardContent'
import CardActions from '@mui/material/CardActions'
import FavoriteIcon from '@mui/icons-material/Favorite'
import { useSnackbar } from 'notistack'

import avatar from '@/assets/images/defaultAvatar.jpeg'
import settings from '@/settings'
import dayjs from '@/utils/date-format'
import { likeMoment } from '@/api/moment'
import { useAppDispatch } from '@/app/hooks'
import { addLikeId } from '@/app/reducer/momentSlice'
import MarkdownRenderer from '@/components/MarkdownRenderer'

import { MomentItemWrap } from './styled'

function MomentItem({ data, likeIds }) {
  const [likes, setLikes] = useState(data.likes)
  const dispatch = useAppDispatch()
  const { enqueueSnackbar } = useSnackbar()
  const handleLike = async (id) => {
    if (likeIds.indexOf(id) > -1) {
      enqueueSnackbar('不可以重复点赞哦')
      return
    }

    try {
      const res: any = await likeMoment(id)
      if (res.code === 200) {
        dispatch(addLikeId(id))
        setLikes((prev) => prev + 1)
      } else {
        enqueueSnackbar(res.msg)
      }
    } catch {
      enqueueSnackbar('异常错误', { variant: 'error' })
    }
  }

  return (
    <MomentItemWrap>
      <div className="moment-inner">
        <Card className="moment-card" variant="outlined">
          <CardHeader
            avatar={<Avatar src={settings.avatar && avatar} />}
            title={settings.author}
            subheader={dayjs(data.createTime).format('YYYY-MM-DD HH:mm')}
          />
          <CardContent>
            <div className="card-content">
              <MarkdownRenderer content={data.content} />
            </div>
          </CardContent>
          <CardActions>
            <span className="tool-btn" onClick={() => handleLike(data.id)}>
              <span className="icon-wrap">
                <span className="icon">
                  <FavoriteIcon
                    fontSize="small"
                    className={likeIds.indexOf(data.id) > -1 ? 'like' : ''}
                  />
                </span>
                <span className="likes">{likes}</span>
              </span>
            </span>
          </CardActions>
        </Card>
      </div>
    </MomentItemWrap>
  )
}

export default MomentItem
